from rest_framework import serializers

from areas.models import Area
from goods.models import SKU
from goods.search_indexes import SKUIndex
from goods.serializers import SKUSerializer
from oauth.models import OAuthQQUser
from users.models import User, Address
from django_redis import get_redis_connection
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings
import re
from rest_framework_jwt.settings import api_settings
from drf_haystack.serializers import HaystackSerializer
from django_redis import get_redis_connection


class CartsSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    def validate(self, attrs):
        # 校验商品是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        # 校验购买数量是否大于库存
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('商品库存不足')

        return attrs


class CartsSKUSerializer(serializers.ModelSerializer):
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)

    class Meta:
        model = SKU
        fields = '__all__'

class CartsDeleteSerializer(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)


    def validate(self, attrs):
        # 校验商品是否存在
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs

class CartsSelectionSerializer(serializers.Serializer):
    selected=serializers.BooleanField()
